package com.wego.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wego.bean.PageBean;
import com.wego.converter.CommentConverter;
import com.wego.converter.UserLikeRelationConverter;
import com.wego.domain.dto.UserLikeRelationDTO;
import com.wego.domain.entity.Comment;
import com.wego.domain.entity.Strategy;
import com.wego.domain.entity.UserLikeRelation;
import com.wego.domain.query.UserLikeRelationQuery;
import com.wego.mapper.CommentMapper;
import com.wego.mapper.StrategyMapper;
import com.wego.mapper.UserLikeRelationMapper;
import com.wego.service.UserLikeRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserLikeRelationServiceImpl implements UserLikeRelationService {
    @Autowired
    private UserLikeRelationMapper userLikeRelationMapper;
    @Autowired
    private UserLikeRelationConverter userLikeRelationConverter;
    
    @Autowired
    private StrategyMapper strategyMapper;
    
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommentConverter commentConverter;

    @Override
    public PageBean<UserLikeRelation> getPage(UserLikeRelationQuery userLikeRelationQuery) {
        final Integer pageNum = userLikeRelationQuery.getPageNum();
        final Integer pageSize = userLikeRelationQuery.getPageSize();
        final Page<UserLikeRelation> page = PageHelper.startPage(pageNum, pageSize);
        userLikeRelationMapper.selectWithCondition(userLikeRelationQuery);
        return PageBean.page2pageBean(page);
    }

    @Override
    public UserLikeRelation getById(Integer id) {
        return userLikeRelationMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(UserLikeRelation userLikeRelation) {
        if (userLikeRelation == null) {
            throw new IllegalArgumentException("UserLikeRelation cannot be null");
        }
        if (userLikeRelation.getUserId() == null) {
            throw new IllegalArgumentException("User ID cannot be null");
        }
        if (userLikeRelation.getEntityType() == null) {
            throw new IllegalArgumentException("Entity type cannot be null");
        }
        //设置更新时间为当前时间
        userLikeRelation.setCreateTime(LocalDateTime.now());
        userLikeRelation.setUpdateTime(LocalDateTime.now());
        return userLikeRelationMapper.insertSelective(userLikeRelation);
    }

    @Override
    public int deleteById(Integer id) {
        return userLikeRelationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer Update(UserLikeRelation userLikeRelation) {
        if (userLikeRelation == null) {
            throw new IllegalArgumentException("UserLikeRelation cannot be null");
        }
        if (userLikeRelation.getId() == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
        return userLikeRelationMapper.updateByPrimaryKeySelective(userLikeRelation);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean isLike(UserLikeRelationDTO userLikeRelationDTO) {
        // 1. 检查是否已经点过赞
        UserLikeRelationQuery userLikeRelationQuery = new UserLikeRelationQuery();
        userLikeRelationQuery.setUserId(userLikeRelationDTO.getUserId());
        userLikeRelationQuery.setEntityType(userLikeRelationDTO.getEntityType());
        userLikeRelationQuery.setEntityId(userLikeRelationDTO.getEntityId());
        PageBean<UserLikeRelation> pageBean = getPage(userLikeRelationQuery);
        if (!pageBean.getRecords().isEmpty()) {
            // 已经点过赞，不能重复点赞
            return false;
        }


        return true;
    }
    /**
     * 点赞功能
     * 1. 在点赞关系表中增加对应的点赞数据（增加前检查是否已经点过赞，避免重复）
     * 2. 在对应的文章或评论的点赞数量加一
     *
     * @param userLikeRelationDTO 点赞
     * @return 是否点赞成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean like(UserLikeRelationDTO userLikeRelationDTO) {
        // 1. 检查是否已经点过赞
        UserLikeRelationQuery userLikeRelationQuery = new UserLikeRelationQuery();
        userLikeRelationQuery.setUserId(userLikeRelationDTO.getUserId());
        userLikeRelationQuery.setEntityType(userLikeRelationDTO.getEntityType());
        userLikeRelationQuery.setEntityId(userLikeRelationDTO.getEntityId());
        PageBean<UserLikeRelation> pageBean = getPage(userLikeRelationQuery);
        if (!pageBean.getRecords().isEmpty()) {
            // 已经点过赞，不能重复点赞
            return false;
        }
        UserLikeRelation userLikeRelation = userLikeRelationConverter.dto2entity(userLikeRelationDTO);
        // 2. 插入点赞记录
        userLikeRelationMapper.insertSelective(userLikeRelation);
        
        // 3. 更新对应文章或评论的点赞数量
        if (userLikeRelation.getEntityType() == 1) { // 评论
            Comment comment = commentMapper.selectByPrimaryKey(userLikeRelation.getEntityId());
            if (comment != null) {
                comment.setLikeCount(comment.getLikeCount() == null ? 1 : comment.getLikeCount() + 1);
                commentMapper.updateByPrimaryKeySelective(comment); // 修改点赞数
            }
        } else { // 文章
            Strategy strategy = strategyMapper.selectByPrimaryKey(userLikeRelation.getEntityId());
            if (strategy != null) {
                strategy.setLikeCount(strategy.getLikeCount() == null ? 1 : strategy.getLikeCount() + 1);
                strategyMapper.updateByPrimaryKeySelective(strategy);
            }
        }
        
        return true;
    }

    /**
     * 取消点赞功能
     * 1. 删除点赞数据（删除前判断是否存在）
     * 2. 在对应文章或评论的点赞数量减一
     *
     * @return 是否取消点赞成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unlike(UserLikeRelationDTO userLikeRelationDTO) {
        // 1. 检查点赞记录是否存在
        UserLikeRelationQuery query = new UserLikeRelationQuery();
        query.setUserId(userLikeRelationDTO.getUserId());
        query.setEntityType(userLikeRelationDTO.getEntityType());
        query.setEntityId(userLikeRelationDTO.getEntityId());
        
        PageBean<UserLikeRelation> pageBean = getPage(query);
        if (pageBean.getRecords().isEmpty()) {
            // 点赞记录不存在，无法取消点赞
            return false;
        }
        
        // 2. 删除点赞记录
        UserLikeRelation likeRelation = pageBean.getRecords().get(0);
        userLikeRelationMapper.deleteByPrimaryKey(likeRelation.getId());
        
        // 3. 更新对应文章或评论的点赞数量
        if (likeRelation.getEntityType() == 1) { // 评论
            Comment comment = commentMapper.selectByPrimaryKey(likeRelation.getEntityId());
            if (comment != null && comment.getLikeCount() != null && comment.getLikeCount() > 0) {
                comment.setLikeCount(comment.getLikeCount() - 1);
                commentMapper.updateByPrimaryKeySelective(comment);
            }
        } else { // 文章
            Strategy strategy = strategyMapper.selectByPrimaryKey(likeRelation.getEntityId());
            if (strategy != null && strategy.getLikeCount() != null && strategy.getLikeCount() > 0) {
                strategy.setLikeCount(strategy.getLikeCount() - 1);
                strategyMapper.updateByPrimaryKeySelective(strategy);
            }
        }
        
        return true;
    }
}